/*
 * Created on Mar 5, 2004
 */
package com.scalar.chiptrack.operations.packingslip.actions;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.util.LabelValueBean;

import com.scalar.ScalarException;
import com.scalar.chiptrack.ChipTrackAction;
import com.scalar.chiptrack.commons.ClientInfo;
import com.scalar.chiptrack.commons.Constants;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.chiptrack.operations.packingslip.CustomerShippingLineItems;
import com.scalar.chiptrack.operations.packingslip.dao.NewPackingSlipDAO;
import com.scalar.chiptrack.operations.packingslip.dao.PackingSlipDAO;
import com.scalar.chiptrack.operations.packingslip.forms.PackingSlipForm;
import com.scalar.chiptrack.operations.vendor.dao.VendorDAO;
import com.scalar.chiptrack.sales.dao.SalesDAO;
import com.scalar.chiptrack.users.User;
import com.scalar.chiptrack.users.dao.UserDAO;

/**
 * @author Ravikanth
**/
public class SavePackingSlipAction  extends ChipTrackAction
{
	public ActionForward execute ( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response ) throws Exception 
	{
		HttpSession session 	= request.getSession();
		String returnVal 		= "failure";
		String action 			= request.getParameter( "action" );
		int customerShippingId  = -1;
		HashMap errors			= new HashMap();
		HashMap lineItemMap 	= null;
		HashMap finalInventoryMap= null;
		boolean dropShip		= false;
		boolean confirmPackingSlip 		= false;
 		PackingSlipForm packingSlipForm = ( PackingSlipForm ) form;
 		User user 						= ( User ) session.getAttribute ( SessionKeys.USER_KEY );
		String currentUser 				= user.getUserId();

		// Validate the Form		
		errors = validateForm ( packingSlipForm, session );
        if ( errors == null )
        {
            errors = new HashMap();
        }

        if ( errors.isEmpty() == true )
 		{
             //VALIDATE INVOICE#
             //Check for the PackingSlip Invoice Number
            /*if ( NewPackingSlipDAO.isPackingSlipInvNoExist ( null, packingSlipForm.getInvNo() ) ) //REGENERATE AND BACK TO THE SAME PAGE
            {
                packingSlipForm.setAction( "loadSalesOrder" );
                packingSlipForm.setInvNo( PackingSlipDAO.getNextPsInvoiceNumber() );
                String salesOrderId 		= request.getParameter ( "salesOrderId" );
                String vendorLocationId     = request.getParameter ( "shippingFromLocationId" );
                ArrayList packingSlipListBySalesOrderId = NewPackingSlipDAO.loadPackingSlipsBySalesOrderId ( Integer.parseInt( salesOrderId ), Constants.CUSTOMER_SHIPPING_STATUS_ISSED );
                ArrayList holdLineItemList = NewPackingSlipDAO.loadLineItemDetails( Integer.parseInt( salesOrderId), Integer.parseInt( vendorLocationId ), "HOLD", null);
                request.setAttribute ( "packingSlipListBySalesOrderId",  setPackingSlipOrder ( packingSlipListBySalesOrderId , packingSlipForm.getLabel() ) );
                request.setAttribute ( "HoldLineItemList", holdLineItemList );
                session.setAttribute ( "packingSlipForm", packingSlipForm );
                String vendorLocationName = VendorDAO.getLocationByAddressId( Integer.parseInt(vendorLocationId), Constants.LOCATION_TYPE_FINISHED_GOODS );
                request.setAttribute( "vendorLocationName", vendorLocationName );
                errors.put ( "Invoice# has been regenerated as it is already exists ", null );
                errors.put ( "Please save the Packing Slip", null );
                request.setAttribute( SessionKeys.ERROR_MESSAGES ,errors );
                return mapping.findForward("success"); //forwarding to submitted page
            }
            else*/
            {
                try
                {
                    finalInventoryMap 		= (HashMap) session.getAttribute ( SessionKeys.FINAL_INVENTORY_MAP );

                    if ( "true".equalsIgnoreCase ( request.getParameter ( "autoConfirmPackingSlip" ) ) )
                    {
                        confirmPackingSlip = true;
                    }

                    //******** Start Here Added by Krishna Prasad on 24 May 2004 *************//
                    /*
                    *   Here we are storing the Shipping Address, Billing Address and Vendor Address
                    *   Objects Again in the Address tables as the Addresses and Contact persons can change for the
                    *   Customer, Vendor and it is getting affected in all the previous packing Slips also
                    */


                    PackingSlipForm psf = ( PackingSlipForm ) session.getAttribute ( "packingSlipForm" );

                    packingSlipForm.setShippingAddressObject( psf.getShippingAddressObject() );
                    packingSlipForm.setBillingAddressObject( psf.getBillingAddressObject() );
                    packingSlipForm.setShippingFromLocationId( psf.getShippingFromAddressId() );
                    packingSlipForm.setCustomerNumber( psf.getCustomerNumber() ); // Added by Krishna 17 June 2004
                    packingSlipForm.setComments( packingSlipForm.getComments()+ "\n" + NewPackingSlipDAO.getMadeInCountryForPartNumber( packingSlipForm.getLineitems() ) );

                    //******** Ends Here ****************************************//

                    customerShippingId = NewPackingSlipDAO.saveCustomerShippingInfo ( packingSlipForm, finalInventoryMap, currentUser, confirmPackingSlip);

                    session.removeAttribute( SessionKeys.FINAL_INVENTORY_MAP );
                    session.removeAttribute( "repetedPartNumber" );
                    packingSlipForm.setCustomerShippingId ( customerShippingId );

                    returnVal = "packingSlipView";
                }
                catch (ScalarException se)
                {
                    // couldnt save customer_shipping information
                    se.getRootCause().printStackTrace();
                    errors.put ("Couldnot save the packing slip", null);
                 }
            }
         }
		 else
		 {
		 	request.setAttribute( SessionKeys.ERROR_MESSAGES ,errors );
			returnVal = "packingSlipMenu";
		 }
		
		//if( returnVal.equalsIgnoreCase( "packingSlipView" ) )
        if( returnVal.equalsIgnoreCase( "packingSlipView" ) )
		{
			ClientInfo clientInfo = new ClientInfo();
			clientInfo = UserDAO.getClientAddressInfo();
		
			packingSlipForm = NewPackingSlipDAO.loadPackingSlipById ( customerShippingId );
			packingSlipForm.setFinalInventoryDataMap( NewPackingSlipDAO.loadLotNumberDataByCustomerShippingId( packingSlipForm.getCustomerShippingId() ) );
            packingSlipForm.setFinalInventoryDataMapView( packingSlipForm.getFinalInventoryDataMap() );
			//packingSlipForm.setCustomerShippingId( customerShippingId );
			//packingSlipForm.setShippingAddressObject( UserDAO.loadAddressById ( packingSlipForm.getShippingToAddressId() ) );
			packingSlipForm.setClientInfo( clientInfo );
			session.setAttribute ( "packingSlipForm", packingSlipForm );
            //Added by varma to show the terms and conditions in PF versions
            request.setAttribute ( "termsAndConditions", SalesDAO.loadTermsAndConditionsAsList () );
			request.setAttribute ( "showMainMenu", "TRUE" );
		}

 		return ( mapping.findForward ( returnVal ) );
 		
		/* 
		// SEND MAIL TO VENDOR
		//if (returnVal.equalsIgnoreCase ("packingSlipView")) {
		//    String host = request.getHeader ("HOST");
		//    String packingSlipAsHTML = formatAsHTML (host, packingSlipForm, orderLineItemList, lineItemMap, finalInventoryMap);
		//
		//    String to = null;
		//    try {
		//        Address vendorAddress = VendorDAO.getVendorAddress(packingSlipForm.getShippingToAddressId(), -1 , false );
		//        to = vendorAddress.getEmail();
		//    }
		//    catch (ScalarException se) {
				// Could not get vendor email address
				 // log it
		//        System.out.println ("Could not get vendor email address, exception - " + se);
		//   }
		//
		//    if (to != null) {
		//        String from = ConfigManager.getSysAdminEmail();
		//        String subject = "Packingslip - " + packingSlipForm.getLabel();
		//        String message = "Packing slip " + packingSlipForm.getLabel() + " is attached";
		//
		//        sendPackingSlipMail (from, to, subject, message, packingSlipAsHTML);
		//    }
		//} */		

	}
	
	private HashMap validateForm ( PackingSlipForm packingSlipForm, HttpSession session ) throws ScalarException {

		HashMap errors 					= new HashMap();
		HashMap finalInventoryMap 		= null;
		HashMap finalInventoryActionErrors = new HashMap();

		// Check for the PackingSlip Form
		if ( packingSlipForm == null )
		{
			errors.put ( "Internal Server Error occured while processing the request", null );
			return errors;
		}

		//Check for the PackingSlip Label
		if ( ( packingSlipForm.getLabel() == null ) || ( packingSlipForm.getLabel().trim().length() == 0 ) )
		{
			errors.put ("Label", "Packingslip Label is invalid");
		}
		else if ( NewPackingSlipDAO.doesPackingSlipLabelExist ( packingSlipForm.getLabel() ) == true )
		{
			errors.put ("Label", "Packing Slip Label, " + packingSlipForm.getLabel() + " already exists");
		}

		// Check for the LineItems selected
		if( ( packingSlipForm.getLineitems() == null ) || ( packingSlipForm.getLineitems().isEmpty() == true ) )
		{
			errors.put( "Could not save Packing Slip, No lineItems available ", null );
		}

		// Fetch any errors in Final Inventory Screen
		finalInventoryActionErrors = ( HashMap ) session.getAttribute ( "FINAL_INVENTORY_ACTION_ERRORS" );
		session.removeAttribute ( "FINAL_INVENTORY_ACTION_ERRORS" );
		if ( ( finalInventoryActionErrors != null ) && ( finalInventoryActionErrors.isEmpty() == false ) )
		{
			errors.putAll ( finalInventoryActionErrors );
		}

		// Check if the Final Inventory Quantity Pull is Available
		finalInventoryMap 		= (HashMap) session.getAttribute ( SessionKeys.FINAL_INVENTORY_MAP );
		if ( finalInventoryMap == null && !packingSlipForm.isDropShippment() )
		{
			errors.put ( "Couldnt save Packing Slip, Lot Information could not be retrived", null );
		}

		// Check for the Number of Boxes
		try
		{
			if ( ( packingSlipForm.getNoOfBoxes() != null ) && ( packingSlipForm.getNoOfBoxes().trim().length() != 0 ) )
			{
				Integer.parseInt ( packingSlipForm.getNoOfBoxes() );
			}
		}
		catch ( NumberFormatException nfe )
		{
			errors.put ( "No Of Boxes", "Not a number, please enter a valid number" );
		}

		// Check for the Ship Date
		// for Drop Shipment the Ship date is entered only while confirming the Packing Slip.

		if ( ( !packingSlipForm.isDropShippment() ) && ( ( packingSlipForm.getShipDate() == null ) || ( packingSlipForm.getShipDate().trim().length() == 0 ) ) )
		{
			errors.put ( "Ship Date", "Please enter a valid Ship Date" );
		}
		else if( packingSlipForm.isDropShippment() && ( packingSlipForm.getShipDate() != null ) && packingSlipForm.getShipDate().trim().length() == 0 )
		{
			packingSlipForm.setShipDate( null );
		}

        if( packingSlipForm.getEtd() != null && packingSlipForm.getEtd().trim().length() == 0 )
		{
			packingSlipForm.setEtd( null );
		}
        if( packingSlipForm.getEta() != null && packingSlipForm.getEta().trim().length() == 0 )
		{
			packingSlipForm.setEta( null );
		}

        return errors;
	}
    private ArrayList setPackingSlipOrder ( ArrayList packingSlipListBySalesOrderId , String currentLabel )
	{
		ArrayList   packingSlipListBySalesOrderId1 = new ArrayList();
	    try
		{
			Iterator packingSlip = packingSlipListBySalesOrderId.iterator();

			while ( packingSlip.hasNext() )
		 	{
				LabelValueBean packingSlipId = ( LabelValueBean )packingSlip.next();
				String label = packingSlipId.getLabel();
				if ( ! label.equalsIgnoreCase( currentLabel ) )
				{
					packingSlipListBySalesOrderId1.add( packingSlipId );
				}
			}
		}
		catch ( Exception e )
		{
			System.out.println (e);
		}
		return packingSlipListBySalesOrderId1;
	}
}